<?php

namespace App\Api\Controller\Security;

use Core\Application\Controller;
use G\User\AuthService;

class AuthController extends Controller
{
    protected $authService;

    public function __construct()
    {
        parent::__construct();

        $this->authService = AuthService::getInstance();
    }

    /**
     * 账号登录
     */
    public function login()
    {
        // 获取参数
        $account = $this->request->getUser();
        $password = $this->request->getPassword();

        // 登录认证
        if ($account && $password) {
            $this->authService->login($account, $password);

            // 获取状态
            if ($this->authService->check()) {
                return $this->success([
                    'token' => $this->authService->token(),
                    'expire' => $this->authService->expire(),
                ]);
            }
        }

        return $this->fail("认证失败");
    }

    /**
     * 使用微信登录
     */
    public function loginWechat()
    {
        $code = $this->request->get('code');

        // 登录认证
        if ($code) {
            $this->authService->loginWeChat($code);

            // 获取状态
            if ($this->authService->check()) {
                return $this->success([
                    'token' => $this->authService->token(),
                    'expire' => $this->authService->expire(),
                ]);
            }
        }

        return $this->fail("认证失败");
    }
}
